package com.base.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.base.vo.Field;
import com.base.vo.Filters;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义的条件构造器,用于后续同环比拦截器中，获取字段以用来拼接条件
 *
 * @author wnhuang
 * @Package com.base.query
 * @date 2021/7/9 16:32
 */
public class CustomizeQueryWrapper<T> extends QueryWrapper<T> {
    private List<Field> selectList;

    private List<Field> groupList;

    private List<Filters> whereList;

    private List<Field> orderByList;

    public QueryWrapper select(List<Field> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            this.selectList = list;
            String[] strings = this.selectList.stream()
                    .map(t -> t.getExpression() + " AS \"" + t.getName() + "\"")
                    .collect(Collectors.toList())
                    .toArray(new String[this.selectList.size()]);
            this.select(strings);
        }
        return typedThis;
    }

    public QueryWrapper<T> groupByField(List<Field> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            this.groupList = list;
            return this.groupBy(list.stream().map(t -> t.getExpression()).collect(Collectors.toList()));
        }
        return null;
    }

    public QueryWrapper<T> orderBy(List<Field> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            this.orderByList = list;
            List<String> descList = list.stream().filter(t -> "desc".equals(t.getSortMode())).map(t -> t.getExpression()).collect(Collectors.toList());
            List<String> ascList = list.stream().filter(t -> !"desc".equals(t.getSortMode())).map(t -> t.getExpression()).collect(Collectors.toList());
            this.orderByDesc(descList);
            return this.orderByAsc(ascList);
        }
        return null;
    }
}
